const db = require("@/db/index");

// 分页查询部门列表
exports.queryDepartment = (req, resp) => {
    try {
        const {
            pageSize,
            pageNum,
            departmentName,
            position,
        } = req.body;

        // 构建查询条件
        let conditions = [];
        let params = [];
        if (departmentName) {
            conditions.push("department_name LIKE ?");
            params.push(`%${departmentName}%`);
        }
        if (position) {
            conditions.push("position LIKE ?");
            params.push(`%${position}%`);
        }

        // 组装WHERE子句
        const whereClause =
            conditions.length > 0 ? " WHERE " + conditions.join(" AND ") : "";

        // 查询总数
        const countSql = `SELECT COUNT(*) as total FROM department ${whereClause}`;
        db.query(countSql, params, (err, totalResult) => {
            if (err) return resp.err(err);
            const total = totalResult[0].total;

            // 查询数据
            let offset = null;
            if (pageNum) offset = (pageNum - 1) * pageSize;
            // const offset = (pageNum - 1) * pageSize;
            let dataSql = `
                SELECT * FROM department 
                ${whereClause} 
                ORDER BY create_time DESC 
            `;

            if (pageNum && pageSize) dataSql += ' LIMIT ? OFFSET ?'

            db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
                if (err) return resp.err(err);

                resp.ok({
                    total,
                    list: rows,
                    pageSize,
                    pageNum,
                });
            });
        });
    } catch (error) {
        resp.err(error);
    }
};

// 新增部门
exports.addDepartment = (req, resp) => {
    try {
        const departmentInfo = req.body;

        // 验证必填字段
        if (!departmentInfo.departmentName) {
            return resp.err("部门名称不能为空");
        }

        // 构建插入数据
        const insertData = {
            department_name: departmentInfo.departmentName,
            position: departmentInfo.position || null,
        };

        // 插入部门数据
        const insertSql = "INSERT INTO department SET ?";
        db.query(insertSql, insertData, (err, result) => {
            if (err) {
                console.error("添加部门失败:", err);
                return resp.err("添加部门失败: " + err.message);
            }
            if (result.affectedRows !== 1) {
                return resp.err("添加部门失败!");
            }
            resp.ok(
                {
                    id: result.insertId,
                    ...insertData,
                    create_time: new Date(),
                },
                "添加部门成功"
            );
        });
    } catch (error) {
        console.error("添加部门异常:", error);
        resp.err("添加部门失败: " + error.message);
    }
};

// 删除部门
exports.deleteDepartment = (req, resp) => {
    try {
        const { ids } = req.body;

        // 验证必填字段
        if (!ids || !Array.isArray(ids) || ids.length === 0) {
            return resp.err("部门ID列表不能为空");
        }

        // 删除部门数据
        const deleteSql = "DELETE FROM department WHERE id IN (?)";
        db.query(deleteSql, [ids], (err, result) => {
            if (err) {
                console.error("删除部门失败:", err);
                return resp.err("删除部门失败: " + err.message);
            }
            if (result.affectedRows === 0) {
                return resp.err("未找到要删除的部门!");
            }
            resp.ok(
                {
                    deletedCount: result.affectedRows,
                },
                `成功删除${result.affectedRows}个部门`
            );
        });
    } catch (error) {
        console.error("删除部门异常:", error);
        resp.err("删除部门失败: " + error.message);
    }
};

// 修改部门信息
exports.updateDepartment = (req, resp) => {
    try {
        const departmentInfo = req.body;

        // 验证是否提供了部门ID
        if (!departmentInfo.id) {
            return resp.err("部门ID不能为空");
        }



        // 更新部门数据
        const updateSql = "UPDATE department SET ? WHERE id = ?";
        db.query(updateSql, [departmentInfo, departmentInfo.id], (err, result) => {
            if (err) {
                console.error("修改部门信息失败:", err);
                return resp.err("修改部门信息失败: " + err.message);
            }
            if (result.affectedRows === 0) {
                return resp.err("未找到该部门!");
            }

            // 查询更新后的部门信息
            const selectSql = "SELECT * FROM department WHERE id = ?";
            db.query(selectSql, [departmentInfo.id], (err, rows) => {
                if (err) {
                    console.error("查询更新后的部门信息失败:", err);
                    return resp.err("查询更新后的部门信息失败: " + err.message);
                }
                if (rows.length === 0) {
                    return resp.err("未找到该部门!");
                }

                resp.ok(rows[0], "修改部门信息成功");
            });
        });
    } catch (error) {
        console.error("修改部门信息异常:", error);
        resp.err("修改部门信息失败: " + error.message);
    }
};
